package com.bac.rentmap.web.controller.ad.manage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.FlatAdDao;
import com.bac.rentmap.ad.flat.crawler.FlatCrawledAd;
import com.bac.rentmap.ad.flat.crawler.FlatCrawledAdDao;
import com.bac.rentmap.ad.flat.rating.BetterFlatAdProvider;
import com.bac.rentmap.ad.flat.rating.FlatAdRatingCalculator;
import com.bac.rentmap.web.controller.ad.add.AddFlatController;

public class FlatAdViewController extends AbstractController {
    private FlatAdDao flatAdDao;
    private FlatCrawledAdDao flatCrawledAdDao;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
//        HttpSession session = request.getSession(false);
//        if (session != null && session.getAttribute(AddFlatController.JUST_ADDED) != null) {
//            return displayMessageForJustAddedFlatAd(session);
//        }
        String secureId = request.getParameter("secureId");
        FlatAd flatAd = flatAdDao.getBySecureId(secureId);
        if (flatAd != null) {
            // flat is displayed in ad list
            return displayFlatAd(flatAd);
        } else {
            return displayMessageForNonTransformedFlatCrawledAd(secureId);
        }
    }

    private ModelAndView displayFlatAd(FlatAd flatAd) {

        ModelAndView res = new ModelAndView("ad/manage/view/view");
        res.addObject("flatAd", flatAd);
        return res;
    }

    private ModelAndView displayMessageForNonTransformedFlatCrawledAd(
            String secureId) {
        FlatCrawledAd flatCrawledAd = flatCrawledAdDao.getBySecureId(secureId);
        ModelAndView res = buildMessageModelAndView();
        res.addObject("flatCrawledAd", flatCrawledAd);
        return res;
    }

//    private ModelAndView displayMessageForJustAddedFlatAd(HttpSession session) {
//        session.removeAttribute(AddFlatController.JUST_ADDED);
//        ModelAndView res = buildMessageModelAndView();
//        res.addObject(AddFlatController.JUST_ADDED, Boolean.TRUE);
//        return res;
//    }

    private ModelAndView buildMessageModelAndView() {
        return new ModelAndView("ad/manage/message");
    }

    @Required
    public void setFlatAdDao(FlatAdDao flatAdDao) {
        this.flatAdDao = flatAdDao;
    }

    @Required
    public void setFlatCrawledAdDao(FlatCrawledAdDao flatCrawledAdDao) {
        this.flatCrawledAdDao = flatCrawledAdDao;
    }

}
